<template>
    <van-sticky>
        <van-nav-bar
            title="邮箱认证"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        />
    </van-sticky>

    <div class="user">
        <div class="user-image">
            <img :src="business.avatar_cdn" />
        </div>
    </div>

    <van-form @submit="email">
        <van-field
            v-model="business.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            readonly
            :rules="[
                {required: true, message: '请输入邮箱'},
                {pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确'}
            ]"
        />
  
        <van-field
            v-model="vercode"
            name="vercode"
            center
            clearable
            label="邮箱验证码"
            placeholder="请输入邮箱验证码"
            :rules="[
                {required: true, message: '请输入邮箱验证码'}
            ]"
        >
            <template #button>
                <van-button size="small" type="primary" @click="send" :disabled="disabled">{{msg}}</van-button>
            </template>
        </van-field>
  
        <div style="width:50%;margin:2em auto;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup>

const {proxy} = getCurrentInstance()

// 获取个人资料信息
const business = proxy.$business;

let vercode = ref('')

let msg = ref('发送验证码')

let disabled = ref(false)

const onBack = () => proxy.$router.back();

const send = async () =>
{
    let params = {
        id:business.value.id,
        email:business.value.email
    }

    disabled.value = true;

    let result = await proxy.$http.post({
        url:'/business/send',
        params
    })

    CountDown();

    if(result.code === 1)
    {
        proxy.$success(result.msg);
    }else{
        proxy.$warning(result.msg);
    }
}

//邮箱验证
const email = async () =>
{
    let params = {
        id:business.value.id,
        code:vercode.value
    }

    let result = await proxy.$http.post({
        url:'/business/email',
        params
    })

    if(result.code === 1)
    {
        proxy.$success({
            message:result.msg,
            onClose:() =>
            {
                proxy.$router.back();
            }
        });
    }else{
        proxy.$fail(result.msg);
    }
}

const CountDown = () =>
{
    let time = 60;
    
    let T = setInterval(() => {

        if(time === 1)
        {
            msg.value = '重新发送验证码';

            disabled.value = false;

            clearInterval(T);

            return false;
        }

        time--;

        msg.value = `${time}秒`;

        
    },1000);
}
</script>

<style scoped>
@import url('/assets/css/BusinessProfile.css');
</style>